package core;

import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.List;

import util.LevelLoader;

import core.units.Unit;

import graphics.Animatable;

public class Game implements Animatable {
	
	private List<Level> myLevels;
	private int myLevelPointer;
	private Level myCurrentLevel;
	
	public Game()
	{
		myLevels = new ArrayList<Level>();
		myLevelPointer = 0;
	}
	/**
	 * Set the game's levels and set the current level to the first in the schema
	 * 
	 * @param schema
	 */
	public void set(String schema) {
		myLevels = LevelLoader.load(schema);
		step();
	}
	
	private void step() {
		try {
			myCurrentLevel = myLevels.get(myLevelPointer);
			myLevelPointer++;	
		} catch (Exception e) {
			return;
		}
	}

	public void animate() {
		myCurrentLevel.update();
		monitor();
		for (Unit mover : myCurrentLevel)
		{
			for (Unit obstacle : myCurrentLevel)
			{
				if (mover.intersects(obstacle))
					mover.collide(obstacle);
				if (mover.isTrashed())
					myCurrentLevel.remove(mover);
			}
		}
		for (Unit mover : myCurrentLevel)
		{
			mover.animate();
		}
	}

	private void monitor() {
		if (myCurrentLevel.lost())
			myCurrentLevel.reset();
	}
	
	public void paint(Graphics2D pen) {
		for (Unit u : myCurrentLevel)
		{
			u.paint(pen);
		}
	}

}
